<!-- 按照部门职务增加教师 -->
<template>
  <div>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      title="按照部门职务增加教师"
      :close-on-click-modal="false"
      top="50px"
      width="850px"
      @close="closeDialog"
    >
      <div class="teacher-box">
        <el-radio-group v-model="type" @change="handleTypeChange">
          <el-radio-button value="1">部门</el-radio-button>
          <el-radio-button value="2">职务</el-radio-button>
        </el-radio-group>
        <div class="search-box">
          <el-input
            placeholder="请输入教师姓名"
            v-model="keyword"
            @keyup.enter="searchTeacher"
            @input="keywordChange"
            clearable
            class="add-input"
          />
          <el-button type="primary" @click="searchTeacher">查询</el-button>
          <span class="selected-num">已选 {{ tableData.length }} 人</span>
          <span class="clear-btn" @click="clearTeacher">清空教师</span>
        </div>
        <div class="table-box" v-loading="loading">
          <div class="left-box">
            <!-- 全选 -->
            <el-checkbox
              v-model="allChecked"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              node-key="id"
              highlight-current
              check-on-click-node
              :expand-on-click-node="false"
              :default-checked-keys="defaultCheckedKeys"
              :props="defaultProps"
            />
          </div>
          <div class="center-box">
            <el-button type="primary" @click="handleCheckChange">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <div class="left-box">
            <el-table :data="tableData" v-loading="tableLoading">
              <el-table-column
                prop="bumen_caption"
                label="部门"
                align="center"
                width="110px"
              />
              <el-table-column
                prop="zhiwu_caption"
                label="职务"
                align="center"
                width="110px"
              />
              <el-table-column prop="xingm" label="姓名" align="center" />
              <el-table-column header-align="center" width="35px">
                <template #default="{ $index }">
                  <el-icon class="close-btn" @click="handleClose($index)"
                    ><CircleCloseFilled
                  /></el-icon>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSubmit"
          class="btn-submit"
          :disabled="loading"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElTree } from "element-plus";
import { ArrowRight, CircleCloseFilled } from "@element-plus/icons-vue";
import { deptTeacherApi, positionTeacherApi } from "@/services/api/flow";
const emits = defineEmits(["closeDialog"]);
const treeRef = ref(ElTree);

let state = reactive({
  dialogVisible: false,
  treeData: [],
  tableData: [],
  deptList: [],
  zwList: [],
  positionList: [],
  loading: false,
  tableLoading: false,
  type: "1",
  keyword: "",
  defaultProps: {
    children: "teachers",
    label: "xingm",
  },
  defaultCheckedKeys: [], //默认选中的节点
  allChecked: false,
  isIndeterminate: false,
});
let {
  dialogVisible,
  treeData,
  tableData,
  loading,
  tableLoading,
  type,
  keyword,
  defaultProps,
  defaultCheckedKeys,
  allChecked,
  isIndeterminate,
} = toRefs(state);

const props = defineProps({
  importVisible: {
    type: Boolean,
    require: true,
    default: false,
  },
  checkedList: {
    type: Array,
    default: () => [],
  },
});
function handleCheckAllChange() {
  if (state.allChecked) {
    treeRef.value.setCheckedNodes(state.treeData);
  } else {
    treeRef.value.setCheckedNodes([]);
  }
}
/**
 * 获取部门教师列表
 */
function getDeptList() {
  return new Promise((resolve, reject) => {
    let params = {};
    if (state.keyword) {
      params.keyword = state.keyword;
    }
    state.loading = true;
    deptTeacherApi(params)
      .then((res) => {
        if (res.code == 1) {
          res.data.forEach((u) => {
            u.xingm = u.caption;
          });
          console.log(res.data);
          state.treeData = res.data;
          state.deptList = res.data;
        }
        state.loading = false;

        resolve(true);
      })
      .catch(() => {
        reject(false);
        state.loading = false;
      });
  });
}
/**
 * 获取职务教师列表
 */
function getPositionList() {
  let params = {};
  if (state.keyword) {
    params.keyword = state.keyword;
  }
  state.loading = true;
  positionTeacherApi(params)
    .then((res) => {
      if (res.code == 1) {
        res.data.forEach((u) => {
          u.xingm = u.caption;
          u.id = u.zhiw;
        });
        state.treeData = res.data;
        state.deptList = res.data;
      }
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
}
/**
 * 搜索教师
 */
function searchTeacher() {
  if (state.type == "1") {
    getDeptList();
  } else {
    getPositionList();
  }
  state.defaultCheckedKeys = [];
  state.tableData.forEach((u) => {
    state.defaultCheckedKeys.push(u.id);
  });
}
function keywordChange() {
  if (!state.keyword) {
    searchTeacher();
  }
}
/**
 * 切换类型
 */
function handleTypeChange(val) {
  state.type = val;
  if (state.keyword) {
    state.keyword = "";
  }
  searchTeacher();
}
/**
 * 选择教师
 */
function handleCheckChange() {
  const checkList = treeRef.value.getCheckedNodes();
  if (checkList.length > 0) {
    checkList.forEach((u) => {
      // 检查state.tableData中是否已经存在相同id的项
      let duplicate = state.tableData.some((u2) => u2.id === u.id);
      // 如果state.tableData中不存在相同id的项，并且有身份证号
      // 则将u添加到state.tableData中
      if (!duplicate && u.shenfzhh) {
        state.tableData.push(u);
      }
    });
  }
}
/**
 * 清空教师
 */
function clearTeacher() {
  state.tableData = [];
  treeRef.value.setCheckedKeys([]);
}
/**
 * 删除教师
 */
function handleClose(index) {
  let nodeKey = state.tableData[index].id;
  treeRef.value.setChecked(nodeKey, false);
  state.tableData.splice(index, 1);
}
/**
 * 保存
 */
function handleSubmit() {
  // if (state.tableData.length == 0) {
  //   ElMessage.warning('请选择教师后保存');
  //   return;
  // }
  let checkedList = [];
  state.tableData.forEach((u) => {
    checkedList.push({
      id: u.id,
      name: u.xingm,
      type: 1,
    });
  });
  emits("closeDialog", checkedList);
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  emits("closeDialog", false);
}
/**
 * 监听父组件传过来的值
 */
async function handleOpenDialog() {
  state.dialogVisible = props.importVisible;
  if (props.importVisible) {
    state.type = "1";
    state.keyword = "";
    await getDeptList();
    state.defaultCheckedKeys = props.checkedList.map((item) => item.id);
    nextTick(() => {
      treeRef.value.setCheckedKeys(state.defaultCheckedKeys);
      state.tableData = [];
      handleCheckChange();
    });
    watch(
      () => treeRef?.value?.getCheckedNodes(),
      () => {
        if (treeRef?.value?.getCheckedNodes()) {
          let checkedNodes = treeRef.value.getCheckedNodes();
          let arr1 = checkedNodes.filter((u) => !u.shenfzhh);
          let arr2 = checkedNodes.filter((u) => u.shenfzhh);
          // 判断父节点是否都选中
          if (arr1.length == state.treeData.length) {
            state.allChecked = true;
            state.isIndeterminate = false;
          } else {
            // 判断子节点有无选中
            if (arr2.length > 0) {
              state.allChecked = false;
              state.isIndeterminate = true;
            } else {
              state.isIndeterminate = false;
              state.allChecked = false;
            }
          }
        }
      },
    );
  }
}

watch(
  () => props.importVisible,
  () => {
    handleOpenDialog();
  },
);
</script>

<style lang="scss" scoped>
.teacher-box {
  .search-box {
    margin-top: 20px;
    .selected-num {
      margin-left: 220px;
      vertical-align: bottom;
    }
    .clear-btn {
      margin-left: 180px;
      color: red;
      cursor: pointer;
      vertical-align: bottom;
    }
    .add-input {
      width: 200px;
      margin-right: 10px;
    }
  }
  .table-box {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    .left-box {
      width: 350px;
      height: 530px;
      padding: 5px;
      box-sizing: border-box;
      border-radius: 5px;
      border: 1px solid #c4c7cf;
      overflow-y: auto;
      .close-btn {
        margin-left: -9px;
        vertical-align: middle;
        font-size: 20px;
        color: #c4c7cf;
        cursor: pointer;
      }
    }
    .center-box {
      padding-top: 250px;
    }
  }
  :deep(.el-tree .el-icon) {
    color: #a8abb2;
  }
  :deep(.el-radio-button__inner) {
    width: 175px;
  }
}
.dialog-footer {
  margin-top: 25px;
  text-align: center;
  .btn-submit {
    width: 200px;
  }
}
</style>
